#!/usr/bin/perl 

my $file='/proc/scsi/scsi';

my $host=0;
my $channel=0;
my $scsiid=0;
my $lun=0;

if( $ARGV[0] eq '-r' ) { 
	$option='remove'; 
} elsif ( $ARGV[0] eq '-a' ) {
	$option='add';
} else {
	&usage();
	exit 1;
}

if(@ARGV==2) { 
	$scsiid=int($ARGV[1]);
} elsif(@ARGV==5) { 
	$host	=int($ARGV[1]);
	$channel=int($ARGV[2]);
	$scsiid	=int($ARGV[3]);
	$lun	=int($ARGV[4]);
} else {
	&usage();
	exit 1;
}

if($option eq 'add') { 
	$k=&findid($host,$channel,$scsiid,$lun);
	if($k==1)  {
		&cleanmd();
		&cleanid($host,$channel,$scsiid,$lun);
	}
}

`echo "scsi $option-single-device $host $channel $scsiid $lun" >$file `;


$k=&findid($host,$channel,$scsiid,$lun);

if( $option eq 'remove' && $k==1 ) { exit 1; } 
if( $option eq 'add'    && $k==0 ) { exit 1; } 
print STDERR "$option $host $channel $scsiid $lun\n";
exit 0;


sub usage
{
	print "Usage: hotswap -[r|a] scsi-id\n";
	print "Usage: hotswap -[r|a] host bus scsi-id lun\n";
}

sub findid
{
	my ($host,$channel,$scsiid,$lun)=@_;

	$line=sprintf("Host: scsi%d Channel: %02d Id: %02d Lun: %02d",
	      $host,$channel,$scsiid,$lun);
	$k=0;
	open(SCSI,$file);
	while(<SCSI>){
		if(/$line/) { $k=1;last;} 
	}
	close(SCSI);
	return $k;
}
sub cleanid
{
	my ($host,$channel,$scsiid,$lun)=@_;
	print $host,$channel,$scsiid,$lun;
	`echo "scsi remove-single-device $host $channel $scsiid $lun" >$file `;
	return 0;
}

sub cleanmd
{
        #added by zy
        system("$config{'remdstat'} >$config{'mdstat'}");
	open(MDSTAT,"/proc/mdstat");
	while(<MDSTAT>){
		if(/^(md\d+) :/) {
			@d=grep(/sd.*\(F\)/,split);
			$md=$1;
			foreach $d (@d) {
				$d =~ s/\[\d+\]\(F\)//;
				`raidhotremove /dev/$md /dev/$d`;
			}
		}
	}
	close(MDSTAT);
	return(0);
}
